<?php
class UserModel extends Zend_Db_Table
{
	protected $_name;      //表名
	protected $_primary;   //主键
	
	private $_output;
	
	protected function _setup()
	{
		$this->_name = 'st_user';
		$this->_primary = 'id';
		
		$this->_output = new Custom_Controller_Plugin_Output();
		parent::_setup();
	}
	
	/**
	 * 用于easyui分页
	 * 
	 * @param array $data 过滤数组
	 * 
	 * @return array
	 */
	public function pageRows(array $data)
	{
		//严格约定，数组键值与字段名必须一致
		$data['page'] = intval($data['page']) - 1;
		
		$select = new Zend_Db_Select($this->getAdapter());
		$select->from('st_user', array('email', 'account', 'id', 'reg_time'));
		$select->joinLeft('st_role', 'st_role.id = st_user.role_id', array('role_name'));
		$select->joinLeft('st_user_account', 'st_user_account.user_id = st_user.id', array('user_amount', 'user_point'));
		
		if(isset($data['search']) && !empty($data['search']))
		{
			$search = json_decode($data['search'], true);
			$select->where('account like ?', '%'.$search['account'].'%');
		}
		
		$select->order($data['sort'].' '.$data['order']);
		$select->limit($data['rows'], $data['page']);
		
		return $this->getAdapter()->fetchAll($select);
	}
	
	/**
	 * 获取指定的数据
	 * 
	 * @param integer $id
	 * @return Ambigous <multitype:, mixed>
	 */
	public function row($id)
	{
		$select = new Zend_Db_Select($this->getAdapter());
		$select->from('st_user');
		$select->where('id=?', $id);
		$select->limit(1);
		
		return $this->getAdapter()->fetchRow($select);
	}
	
	/**
	 * 添加新用户
	 * 
	 * @param array $data
	 * 
	 * @return bool
	 */
	public function add(array $data)
	{
		if(!isset($data['account']) || empty($data['account']))
			return $this->_output->success(false, '没有填写用户帐号');
		
		$select = new Zend_Db_Select($this->getAdapter());
		$select->from('st_user', array('count(id) as _COUNT'));
		$select->where('account = ?', $data['account']);
		$select->limit(1);
		
		$row = $this->getAdapter()->fetchRow($select);
		if($row['_COUNT'] > 0) 
			return $this->_output->success(false, '用户帐号已存在');
		
		
		if(!isset($data['email']) || empty($data['email']))
			return $this->_output->success(false, '没有填写电子邮件');
		
		$select = new Zend_Db_Select($this->getAdapter());
		$select->from('st_user', array('count(id) as _COUNT'));
		$select->where('email = ?', $data['email']);
		$select->limit(1);
		
		$row = $this->getAdapter()->fetchRow($select);
		if($row['_COUNT'] > 0)
			return $this->_output->success(false, '电子邮箱已存在');
		
		
		if(!isset($data['password']) || empty($data['password']))
			return $this->_output->success(false, '没有填写登录密码');
		
		if(strcmp($data['password'], $data['nextpwd']))
			return $this->_output->success(false, '两次密码输入不一致');
		
		unset($data['nextpwd']);
		
		$data['reg_time'] = time();
		$data['last_login'] = 0;
		$data['last_ip'] = '0.0.0.0';
		$data['is_emailcheck'] = 0;
		$data['emailcheck_code'] = md5($data['account'].'_'.time());
		$this->insert($data);
		
		
		//插入数据到账户

		return $this->_output->success(true);
	}
}